package com.rongdu.workflow.listener;

import org.activiti.engine.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 自定义一套规则来处理基于角色的任务分配
 * @author FHJ
 *
 */
@SuppressWarnings("serial")
public class AssigneeAliasTaskListener extends DefaultTaskListener {
	private static Logger logger = LoggerFactory
			.getLogger(AssigneeAliasTaskListener.class);
	
	@Override
	public void onCreate(DelegateTask delegateTask) throws Exception {
		String assigneeString = delegateTask.getAssignee();
		
		if(assigneeString.contains("role:")) {
			assignTaskToOneWithThisRole(delegateTask, assigneeString);
		} else {
			assginTaskDirectly(delegateTask, assigneeString);
		}
	}

	private void assginTaskDirectly(DelegateTask delegateTask,
			String assigneeString) {
		delegateTask.setAssignee(assigneeString);
	}

	private void assignTaskToOneWithThisRole(DelegateTask delegateTask,
			String assigneeString) {
		String role = assigneeString.substring(assigneeString.indexOf(":") + 1);
		
		// 选择一个最不忙的人，把任何给他
		String userId = queryTheLeastBusyPeopleWithThisRole(role);
		
		delegateTask.setAssignee(userId);
	}

	/**
	 * mock
	 * @param role
	 * @return
	 */
	private String queryTheLeastBusyPeopleWithThisRole(String role) {
		if(role.equals("经理")){
			return "3";
		} else if(role.equals("总经理")) {
			return "4";
		} else{
			throw new IllegalArgumentException("queryTheLeastBusyPeopleWithThisRole出错");
		}
		
	}
}
